package com.gm.wj.util;

import com.gm.wj.entity.SysImage;
import com.gm.wj.service.SysImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @program: wj
 * @description:
 * @author: Huang_shengjun
 * @create: 2020-08-22 11:04
 **/
public class ImageUtil {

    @Autowired
    SysImageService sysImageService;

    // 需要改动的还有 MyWebConfigurer

    //读取图片地址
    @Value("${image.url}")
    String ima_folder;

    public String imgUpload(MultipartFile file,String imgType) {
        File imageFolder = new File(ima_folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/" + f.getName();
            SysImage sysImage = new SysImage();
            sysImage.setImageId(StringUtils.getRandomString(6));
            sysImage.setUrl(imgURL);
            sysImage.setFolder(ima_folder);
            sysImage.setImgType(imgType);
            sysImageService.add(sysImage);

            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
